package com.gjt.serverSocket;

import com.gjt.stream.Write;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with Intel IDEA.
 * 多线程的daytime服务器
 * @Auther: gjt
 * @Date: 2024/5/5 9:37
 */
public class MultithreadedDaytimeServer {
    private final static int PORT = 13;

    public static void main(String[] args) {
        try(ServerSocket serverSocket = new ServerSocket(PORT)){
            while(true){
                try{
                    Socket accept = serverSocket.accept();
                    Thread task = new DaytimeThread(accept);
                    task.start();
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        }catch (IOException e){
            System.err.println("don't start server");
        }
    }

    private static class DaytimeThread extends Thread{
        private Socket socket;

        public DaytimeThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try{
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String transformDate = simpleDateFormat.format(new Date());
                out.write(transformDate);
                out.flush();
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                try{
                    socket.close();
                }catch (IOException ignored){}
            }
        }
    }
}
